﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Script.Serialization;
using Medora.Model;
using Medora.Model.Basic;
using Medora.Model.Institutions;
using Medora.Services;


namespace Medora.Web.App_Code
{
    public class DepartmentsController : BaseApiController
    {
        private readonly IDepartmentsService _service;
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        // GET api/<controller>
        public DepartmentsController(IDepartmentsService service )
        {
            _service = service;
        }

        [ActionName("GetByPage")]
        public IPagedEntities<Department> GetByPage(int pageSize, int page, string filter, string ss)
        {
            var user = System.Web.Security.Membership.GetUser(User.Identity.Name);
            if (user != null && user.ProviderUserKey != null)
            {
                var departmentFilter = serializer.Deserialize<DepartmentFilter>(filter);
                SortInfo sort = null;
                if(!string.IsNullOrEmpty(ss)) sort= serializer.Deserialize<SortInfo>(ss);
                var userId = (Guid) user.ProviderUserKey;
                return _service.GetPagedByInstitutionByUserId(pageSize, page, userId, departmentFilter, sort);
            }
            return null;
        }

        [ActionName("GetCount")]
        public int GetCount()
        {
            var user = System.Web.Security.Membership.GetUser(User.Identity.Name);
            if (user != null && user.ProviderUserKey != null)
            {
                return _service.GetCount((Guid)user.ProviderUserKey);
            }
            return 0;
        }

        // GET api/<controller>/5
        public string Get(Guid id)
        {
            return "value";
        }

        // POST api/<controller>
        public HttpResponseMessage Post([FromBody]Department value)
        {
            if (ModelState.IsValid)
            {
                var user = System.Web.Security.Membership.GetUser(User.Identity.Name);
                if (user != null && user.ProviderUserKey != null)
                {
                   Guid userId = (Guid)user.ProviderUserKey;
                   if (_service.Save(userId, value)) return Request.CreateResponse(HttpStatusCode.OK, value);
               }
               return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Please sign in!");
            }
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Validation error");
        }

        // DELETE api/<controller>/5
        [HttpDelete]
        public void Delete(string id)
        {
            var ids = serializer.Deserialize<List<Guid>>(id);
            if(_service.Delete(ids)) Request.CreateResponse(HttpStatusCode.OK);

        }

        [ActionName("GetAutocomplete")]
        public AutoComplete<AutoCompleteItem> GetAutocomplete(string query)
        {
            var autoComplete = new AutoComplete<AutoCompleteItem> { query = query, suggestions = new List<AutoCompleteItem>() };
            var user = System.Web.Security.Membership.GetUser(User.Identity.Name);
            if (user != null && user.ProviderUserKey != null)
            {
                var lst=_service.GetByInstitutionByUserId((Guid) user.ProviderUserKey).Where(o=>o.Title.ToLower().Contains(query.ToLower())).Select(o=>new AutoCompleteItem{data = o.Id.ToString(), value = o.Title});
                autoComplete.suggestions.AddRange(lst);
            }
            return autoComplete;
        }

        [ActionName("GetLazy")]
        public IEnumerable<AutoCompleteItem> GetLazy()
        {
            var user = System.Web.Security.Membership.GetUser(User.Identity.Name);
            if (user != null && user.ProviderUserKey != null)
            {
                return _service.GetByInstitutionByUserId((Guid)user.ProviderUserKey).Select(o => new AutoCompleteItem { data = o.Id.ToString(), value = o.Title }).OrderBy(o=>o.value);
                
            }
            return new List<AutoCompleteItem>();
        }
        
    }
}